package com.day2.hw;

import com.utility.Array;
import com.utility.RandomGenerator;

public class Permutation {

	int count;

	public void permute(Character[] input, Integer[] rule){
		int prev=0;
		int curr=rule[prev];
		
		while(prev<input.length-1){
			if(prev==curr){
				prev++;
				curr=rule[prev];
			}
			if(curr==prev)
				continue;
			Array.swap(input, prev,curr);
			Array.swap(rule,prev,curr);
			curr=rule[prev];
		}
	}
	
	
	public boolean checkAscending(Integer[] A){
		for(int i=1;i<A.length;i++){
			if(A[i]<=A[i-1])
				return false;
		}
		return true;
	}
	
	public void generateTestCase(){
		int count=0;
		for(int length=6;length<7;length++){
			Character[] input=new Character[length];
			Integer[] rule=new Integer[length];
			for(int j=0;j<100000;j++){
				for(int i=0;i<length;i++){
					int val=97+i;
					String s=""+val;
					input[i]=(char)(Integer.parseInt(s));
					rule[i]=i;
				}
				RandomGenerator.getRandomSubarray(rule,rule.length-1);
				System.out.println(rule);
				permute(input, rule);
				if(checkAscending(rule)){
					//System.out.println("Does not work");
					count++;
				}
			}
		}
		System.out.println("Done - test cases passed = "+count);
	}
	
	public void generateTestPermutations(){
		for(int length=6;length<7;length++){
			Integer[] rule=new Integer[length];
			Character[] input=new Character[length];
			for(int i=0;i<length;i++){
				int val=97+i;
				String s=""+val;
				input[i]=(char)(Integer.parseInt(s));
				rule[i]=i;
			}
			count=0;
			generateTestPermutations(rule,input,0);
			System.out.println("permutation for length " + length+" = " + count);
		}
	}
	public void generateTestPermutations(Integer[] rule,Character[] input,int l){
		if(l==rule.length-1)
		{
			Integer[] r=rule.clone();
			permute(input,r);
			if(!checkAscending(r)){
				System.out.println("Does not work");
				count--;
			}
			count++;
			return;
		}
		for(int i=l;i<rule.length;i++){
			Array.swap(rule,l,i);
			generateTestPermutations(rule,input,l+1);
			Array.swap(rule,l,i);
		}
	}
}
